package com.jimmyhsu.ecnudaowei;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewTreeObserver;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jimmyhsu.ecnudaowei.Bean.TaskActivity;
import com.jimmyhsu.ecnudaowei.Db.User;
import com.jimmyhsu.ecnudaowei.Db.UserDbHelper;
import com.jimmyhsu.ecnudaowei.Db.UserInfoProvider;
import com.jimmyhsu.ecnudaowei.coursetable.CourseDetails;
import com.jimmyhsu.ecnudaowei.coursetable.bulletin.BulletinActivity;
import com.jimmyhsu.ecnudaowei.coursetable.checkin.CheckInActivity;
import com.jimmyhsu.ecnudaowei.coursetable.file.FileActivity;
import com.jimmyhsu.ecnudaowei.coursetable.sync.CourseSyncFragment;
import com.jimmyhsu.ecnudaowei.coursetable.CourseTableFragment;
import com.jimmyhsu.ecnudaowei.coursetable.edit.AddOrEditCourseActivity;
import com.jimmyhsu.ecnudaowei.coursetable.view.WheelPickerWindowBuilder;
import com.jimmyhsu.ecnudaowei.login.LoginActivity;
import com.jimmyhsu.ecnudaowei.person.MeActivity;
import com.jimmyhsu.ecnudaowei.person.UserActivity;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.BitmapCallback;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import kotlin.Unit;
import kotlin.jvm.functions.Function2;
import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;

public class MainActivity extends AppCompatActivity {

    private static final int LOADER_ID = 1;
    private static final int MSG_REFRESH_HEAD = 0x110;
    private static final int PERMISSION_REQUEST_CODE = 100;
    private static final int PERMISSION_REQUEST_CODE_LOC = 101;
    public static final int REQUEST_RELEASE_SH = 1;
    public static final int REQUEST_RELEASE_DW = 2;
    private static final String[] MAIN_LABELS = {"主页", "课程表", "我"};
    private static final int[] LABEL_RES = {R.drawable.ic_home_white_48dp,
            R.drawable.ic_event_white_48dp, R.drawable.ic_account_circle_white_48dp};

    //    private RelativeLayout mContainer;

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.id_main_container)
    RelativeLayout mContainer;
    @BindView(R.id.bottom_sheet)
    View mBottomSheet;
    @BindView(R.id.id_ciw_title)
    RelativeLayout mCourseTop;
    @BindView(R.id.id_ciw_back)
    ImageView mCoursePopupBack;
    @BindView(R.id.id_ciw_content)
    RelativeLayout mCourseInfoContentView;
    @BindView(R.id.id_app_bar)
    AppBarLayout mAppBar;
    @BindView(R.id.id_ciw_modify)
    FloatingActionButton mModifyFab;
    @BindView(R.id.id_ciw_delete)
    Button mDeleteCourseView;
    @BindView(R.id.id_ciw_check_in)
    TextView mCheckInView;

    private BroadcastReceiver mReceiver;

    private CourseTableFragment mCtFragment;
    private MyApplication mApplication;
    private int mGoto = 1;
    private BottomSheetBehavior<View> mBottomSheetBehavior;
    private int mBottomSheetPeekHeight;
    private boolean needShow = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        setSupportActionBar(toolbar);
        mApplication = (MyApplication) getApplicationContext();
        boolean needLogin = checkLogin();
        if (needLogin) {
            return;//        mContainer = (RelativeLayout) findViewById(R.id.id_main_container);
        }
//        mSecondHandFragment = new SecondHandFragment();
//        getSupportFragmentManager().beginTransaction().add(R.id.id_main_container, mSecondHandFragment).commit();
//        mSecondHandFragment.initDatas(this);
        mCtFragment = new CourseTableFragment();
        getSupportFragmentManager().beginTransaction().add(R.id.id_main_container,
                mCtFragment).commit();
        initEvents();
        initBottomSheet();
        refreshUserInfos();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            checkPermission();
        }
    }

    private void initBottomSheet() {
        mCourseInfoContentView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                if (!needShow) return true;
                needShow = false;
                int newHeight = mCourseInfoContentView.getMeasuredHeight();
                if (mBottomSheetPeekHeight != newHeight) {
                    mBottomSheetPeekHeight = newHeight;
                    mBottomSheetBehavior.setPeekHeight(mBottomSheetPeekHeight
                            + LoginActivity.dp2px(56, MainActivity.this));
                    mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                }
                return true;
            }
        });
        mBottomSheetBehavior = BottomSheetBehavior.from(mBottomSheet);
        mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
        mBottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {
                if (newState == BottomSheetBehavior.STATE_EXPANDED) {
                    mCoursePopupBack.setVisibility(View.VISIBLE);
                } else {
                    mCoursePopupBack.setVisibility(View.GONE);
                }
                if (newState == BottomSheetBehavior.STATE_HIDDEN) {
                    setCourseFragmentAlpha(1);
                }
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {
                if (slideOffset > 0.8f) {
                    mAppBar.setAlpha(1 - (slideOffset - 0.8f) * 5);
                    mCourseTop.setAlpha((slideOffset - 0.8f) * 5);
                } else if (slideOffset <= 0.8f) {
                    mAppBar.setAlpha(1);
                    mCourseTop.setAlpha(0);
                }
                if (slideOffset < 0) {
                    setCourseFragmentAlpha(1 - 0.4f * (1 - Math.abs(slideOffset)));
                } else if (slideOffset >= 0) {
                    setCourseFragmentAlpha(0.6f);
                }
            }
        });
    }

    private void setCourseFragmentAlpha(float alpha) {
        if (alpha < 0) alpha = 0;
        if (alpha > 1) alpha = 1;
        if (mCtFragment != null) {
            mCtFragment.setAlpha(alpha);
        }
    }

    @OnClick(R.id.id_ciw_back)
    void closeCourseInfoWindow() {
        if (mBottomSheetBehavior != null &&
                mBottomSheetBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED) {
            mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
        }
    }

    private void checkPermission() {
//        Toast.makeText(this, "用于缓存图片和定位功能，请授予哦~", Toast.LENGTH_SHORT).show();
        PermissionGen.with(MainActivity.this)
                .addRequestCode(PERMISSION_REQUEST_CODE)
                .permissions(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_PHONE_STATE)
                .request();
    }

//    @PermissionSuccess(requestCode = PERMISSION_REQUEST_CODE)
//    public void onSuccessPermission(){
//        Log.d("MainActivity", "permission granted");
//    }

    @PermissionFail(requestCode = PERMISSION_REQUEST_CODE)
    public void onFailPermission() {
        Toast.makeText(this, "呜呜~", Toast.LENGTH_SHORT).show();
        finish();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    private void downloadUserHead(final int id) {
        if (id > 0) {
            OkHttpUtils.get().url(LoginActivity.BASE_URL + "phpprojects/userimage/" +
                    id + ".jpg").build().execute(new BitmapCallback() {
                @Override
                public void onError(Request request, Exception e) {

                }

                @Override
                public void onResponse(Bitmap response) {
                    mApplication.setUserHead(response);
                }
            });
        }
    }


    private void refreshUserInfos() {
        UserDbHelper helper = UserDbHelper.getInstance(this);
        SQLiteDatabase db_r = helper.getReadableDatabase();
        Cursor cursor = db_r.rawQuery("select count(*) from " + User.TB_NAME, null);
        cursor.moveToFirst();
//        cursor.moveToNext();
        int userCount = cursor.getInt(0);
        cursor.close();
        db_r.close();
        if (userCount <= 0) {
            insertEmptyInfo();
        }
        downloadUserInfo();
    }

    private void insertEmptyInfo() {
        ContentValues values = new ContentValues();
        values.put(User.COL_NAME, mApplication.getName());
        values.put(User.COL_AGE, 18);
        values.put(User.COL_MOBILE, "unknown");
        values.put(User.COL_REGDATE, new SimpleDateFormat("yyyy年MM月dd日").format(new Date(System.currentTimeMillis())));
        values.put(User.COL_SEX, 1);
        values.put(User.COL_SIGNATURE, "快来填写吧~");
        values.put(User.COL_STU_ID, "unknown");
        values.put(User.COL_USERINFO_ID, 0);
        values.put(User.COL_VERIFIED, 0);
        values.put(User.COL_REALNAME, "");
        getContentResolver().insert(UserInfoProvider.URI_USER_CURRENT, values);
    }

    private void downloadUserInfo() {
//        Log.e("MainActivity", "downloading user info...");
        OkHttpUtils.post().url(LoginActivity.BASE_URL + "phpprojects/getMyInfo.php")
                .addParams("username", mApplication.getName())
                .addParams("deviceid", mApplication.getAndroidId(this))
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Request request, Exception e) {
                        Snackbar.make(mCourseInfoContentView, "网络异常", Snackbar.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject obj = new JSONObject(response);
                            if (obj.getInt("status") == 200) {
                                int id = obj.getInt("id");
                                String mobile = obj.getString("mobile");
                                String sign = obj.getString("signature");
                                String realName = obj.getString("realname");
                                long regdate = obj.getLong("regdate");
                                int sex = obj.getInt("sex");
                                int verified = obj.getInt("verified");
                                String stuId = obj.getString("studentid");
                                int age = obj.getInt("age");
                                ContentValues values = new ContentValues();
                                values.put(User.COL_NAME, mApplication.getName());
                                values.put(User.COL_AGE, age);
                                values.put(User.COL_MOBILE, mobile);
                                values.put(User.COL_REGDATE, new SimpleDateFormat("yyyy年MM月dd日").format(new Date(regdate)));
                                values.put(User.COL_SEX, sex);
                                values.put(User.COL_SIGNATURE, sign);
                                values.put(User.COL_STU_ID, stuId);
                                values.put(User.COL_VERIFIED, verified);
                                values.put(User.COL_REALNAME, realName);
                                values.put(User.COL_USERINFO_ID, id);
//                                Log.e("MainActivity", "stu_id = " + stuId);
//                                Log.e("MainActivity", "verified = " + verified);
                                mApplication.setId(id);
                                mApplication.setRealName(realName);
                                downloadUserHead(id);
//                                mHandler.sendEmptyMessage(MSG_REFRESH_HEAD);
                                getContentResolver().update(UserInfoProvider.URI_USER_CURRENT,
                                        values,
                                        "_id=1", null);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            Log.e("MainActivity", "json err: " + response);
                        }
                    }
                });
    }

    @Override
    protected void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
//        mHandler.sendEmptyMessage(MSG_REFRESH_HEAD);
        View view = getWindow().peekDecorView();
        if (view != null) {
            InputMethodManager inputmanager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputmanager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
//        refreshContainerHeight();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == REQUEST_RELEASE_SH && resultCode == RESULT_OK) {
//            if (mGoto == R.id.nav_secondhand && mSecondHandFragment != null) {
//                mSecondHandFragment.refreshData(this);
//            }
//        } else
//            if (requestCode == REQUEST_RELEASE_DW && resultCode == RESULT_OK) {
//            if (mGoto == R.id.nav_daowei && mDwFragment != null) {
//                mDwFragment.refresh();
//            }
//        }
    }

    private void initEvents() {
//        fab.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
////                if (mGoto == R.id.nav_secondhand) {
////                    Intent intent = new Intent(MainActivity.this, ReleaseNewItemActivity.class);
////                    startActivityForResult(intent, REQUEST_RELEASE_SH);
////                } else if (mGoto == R.id.nav_daowei) {
////                    Intent intent = new Intent(MainActivity.this, ReleaseDwActivity.class);
////                    startActivityForResult(intent, REQUEST_RELEASE_DW);
////                }
//                overridePendingTransition(R.anim.slide_in_bottom, R.anim.slide_out_bottom);
//            }
//        });
//        mBottomBar.init(MAIN_LABELS, LABEL_RES);
        mGoto = 1;
//        mBottomBar.setOnLabelSelectedListener(new BottomBarLayout.OnLabelSelectedListener() {
//            @Override
//            public void labelSelected(int pos) {
//                mGoto = pos;
//                if (pos != R.id.nav_course_table) {
////                    toggleFab(true);
//                    mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
//                }
//                switch (pos) {
//                    case 1:
//                        if (mCtFragment == null) {
//                            mCtFragment = new CourseTableFragment();
//                        }
//                        getSupportFragmentManager().beginTransaction()
//                                .replace(R.id.id_main_container, mCtFragment)
//                                .commit();
////                        toggleFab(false);
//                        break;
//                    case 2:
//                        MeActivity.startActivity(MainActivity.this);
//                        break;
//                }
//                invalidateOptionsMenu();
//            }
//        });
//        mBottomBar.select(1);
        prepareReceiver();
    }

    private void prepareReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(CourseSyncFragment.ACTION_SYNC_SUCCESS);
        filter.addAction(CourseTableFragment.ACTION_TO_SYNC);
        filter.addAction(AddOrEditCourseActivity.ACTION_COURSE_REFRESH);
        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                switch (action) {
                    case CourseSyncFragment.ACTION_SYNC_SUCCESS:
                        if (mGoto == 1) {
                            getSupportFragmentManager().beginTransaction()
                                    .replace(R.id.id_main_container, mCtFragment)
                                    .commit();
                        }
                        break;
                    case CourseTableFragment.ACTION_TO_SYNC:
                        if (mGoto == 1) {
                            getSupportFragmentManager().beginTransaction()
                                    .replace(R.id.id_main_container, new CourseSyncFragment())
                                    .commit();
                        }
                        break;
                    case AddOrEditCourseActivity.ACTION_COURSE_REFRESH:
                        if (mGoto == 1 && mCtFragment != null) {
                            mCtFragment.refresh();
                            if (mBottomSheetBehavior.getState() != BottomSheetBehavior.STATE_HIDDEN)
                                mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
                        }
                        break;
                }
            }
        };
        registerReceiver(mReceiver, filter);
    }


    private void checkLocationPermission() {
        PermissionGen.with(MainActivity.this)
                .addRequestCode(PERMISSION_REQUEST_CODE_LOC)
                .permissions(Manifest.permission.ACCESS_FINE_LOCATION)
                .request();
    }

    @PermissionSuccess(requestCode = PERMISSION_REQUEST_CODE_LOC)
    public void gotoDw() {
//        if (mDwFragment == null) {
//            mDwFragment = new DwFragment();
//        }
//        getSupportFragmentManager().beginTransaction()
//                .replace(R.id.id_main_container, mDwFragment)
//                .commit();
    }

    @PermissionFail(requestCode = PERMISSION_REQUEST_CODE_LOC)
    public void failPermissionLoc() {

    }

    private boolean isFabShown = true;

//    private void toggleFab(boolean show) {
//        if (!show && isFabShown) {
//            ObjectAnimator animator = ObjectAnimator.ofFloat(fab, "translationY", 0,
//                    -LoginActivity.dp2px(-150, this))
//                    .setDuration(300);
//            animator.addListener(new AnimatorListenerAdapter() {
//                @Override
//                public void onAnimationEnd(Animator animation) {
//                    super.onAnimationEnd(animation);
//                    isFabShown = false;
//                }
//            });
//            animator.start();
//        } else if (show && !isFabShown) {
//            ObjectAnimator animator = ObjectAnimator.ofFloat(fab, "translationY",
//                    -LoginActivity.dp2px(-150, this),
//                    0)
//                    .setDuration(300);
//            animator.addListener(new AnimatorListenerAdapter() {
//                @Override
//                public void onAnimationEnd(Animator animation) {
//                    super.onAnimationEnd(animation);
//                    isFabShown = true;
//                }
//            });
//            animator.start();
//        }
//    }

    @OnClick(R.id.id_ciw_modify)
    void modifyCourse() {
        if (mCtFragment != null) {
            TaskActivity currCourse = mCtFragment.getCurrCourse();
            AddOrEditCourseActivity.startActivity(this,
                    currCourse.get_id(),
                    currCourse.getDay(),
                    currCourse.getNumber(),
                    currCourse.getNumber() + currCourse.getDuration() - 1,
                    mCtFragment.getAvailWeek(currCourse.getDay(), currCourse.getNumber(), currCourse.getDuration(), currCourse),
                    mCtFragment.getMaxWeek(),
                    currCourse.getLocation(),
                    currCourse.getTeacher(),
                    currCourse.getCourseWeek(),
                    currCourse.getCourseName(),
                    currCourse.getCourseId(),
                    currCourse.isAddByUser());
        }
    }

    @OnClick(R.id.id_ciw_check_in)
    void checkIn() {
        if (mCtFragment != null && mCtFragment.getCurrCourse() != null) {
            CheckInActivity.startActivity(this, mCtFragment.getCurrCourse().getCourseId());
        } else {
            Toast.makeText(this, "未知异常", Toast.LENGTH_SHORT).show();
        }
    }

    @OnClick(R.id.id_ciw_bulletin)
    void seeBulletin() {
        BulletinActivity.startActivity(this, mCtFragment.getCurrCourse().getCourseId());
    }

    @OnClick(R.id.id_ciw_file)
    void seeFile() {
        FileActivity.startActivity(this, mCtFragment.getCurrCourse().getCourseId());
    }

    @OnClick(R.id.id_ciw_delete)
    void deleteCourse() {
        new AlertDialog.Builder(this)
                .setTitle("删除")
                .setMessage("如果该课程由同步公共数据库得到，删除课程将影响签到等功能，您可通过重新同步恢复，是否继续？")
                .setNegativeButton("取消", null)
                .setPositiveButton("继续", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        UserDbHelper dbHelper = UserDbHelper.getInstance(MainActivity.this);
                        SQLiteDatabase db = dbHelper.getWritableDatabase();
                        if (mCtFragment != null) {
                            TaskActivity course = mCtFragment.getCurrCourse();
                            db.delete(TaskActivity.TB_COURSE, "_id=" + course.get_id(), null);
                            db.close();
                            mCtFragment.refresh();
                            mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
                        }
                    }
                })
                .create()
                .show();
    }


    private boolean checkLogin() {
        SharedPreferences sp = getSharedPreferences(LoginActivity.SP_NAME, MODE_PRIVATE);
        if (!sp.getBoolean(LoginActivity.SP_KEY_ISLOGIN, false)) {
            mApplication.setLogin(false);
            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
            startActivity(intent);
            finish();
            return true;
        } else {
            mApplication.setName(sp.getString(LoginActivity.SP_KEY_NAME, ""));
            mApplication.setPassword(sp.getString(LoginActivity.SP_KEY_PASSWORD, ""));
            mApplication.setLogin(true);
            return false;
        }
    }

    @Override
    public void onBackPressed() {
        if (mBottomSheetBehavior != null
                && mBottomSheetBehavior.getState() != BottomSheetBehavior.STATE_HIDDEN) {
            mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
            return;
        }
        setResult(RESULT_OK);
        super.onBackPressed();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        if (mGoto == 1) {
            if (mCtFragment != null && mCtFragment.isInEditorMode()) {
                MenuItem refreshMenu = menu.add(Menu.NONE, Menu.FIRST + 2, 0, "完成");
                refreshMenu.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
            } else {
                getMenuInflater().inflate(R.menu.main_course, menu);
            }
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (mCtFragment == null) return super.onOptionsItemSelected(item);
        int id = item.getItemId();

        switch (id) {
            case R.id.menu_resync:
                mCtFragment.resync();
                return true;
            case R.id.menu_add_course:
                mCtFragment.enterEditorMode();
                return true;
            case R.id.menu_modify_week:
                new WheelPickerWindowBuilder(this, 1, mCtFragment.getMaxWeek(), "选择周")
                        .setOnDataChosenListener(new Function2<Integer, Object, Unit>() {
                            @Override
                            public Unit invoke(Integer integer, Object o) {
                                mCtFragment.setWeek((Integer) o);
                                return null;
                            }
                        })
                        .setCurrentItem(mCtFragment.getWeek() - 1)
                        .createDialog()
                        .show();
                return true;
            case Menu.FIRST + 2:
                mCtFragment.quitEditorMode(true);
                return true;
            case R.id.menu_me:
                UserActivity.Companion.startActivity(this);
                return true;
            default:
                break;

        }
        return super.onOptionsItemSelected(item);
    }

//    @SuppressWarnings("StatementWithEmptyBody")
//    @Override
//    public boolean onNavigationItemSelected(MenuItem item) {
//        // Handle navigation view item clicks here.
//        int id = item.getItemId();
//        if (id == mGoto) {
//            mDrawer.closeDrawer(GravityCompat.START);
//            return true;
//        }
//        if (id == R.id.nav_secondhand) {
//            mGoto = R.id.nav_secondhand;
//            mSecondHandFragment = new SecondHandFragment();
//            mDrawer.closeDrawer(GravityCompat.START);
//            supportInvalidateOptionsMenu();
//        } else if (id == R.id.nav_daowei) {
//            mGoto = R.id.nav_daowei;
//            mDwFragment = new DwFragment();
//            mDrawer.closeDrawer(GravityCompat.START);
//            supportInvalidateOptionsMenu();
//        } else if (id == R.id.nav_me) {
//            MeActivity.startActivity(this);
//        } else if (id == R.id.nav_logout) {
//            logout();
//        }
//
//        return true;
//    }

    private void logout() {
        SharedPreferences sp = getSharedPreferences(LoginActivity.SP_NAME, MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.remove(LoginActivity.SP_KEY_NAME);
        edit.remove(LoginActivity.SP_KEY_PASSWORD);
        edit.remove(LoginActivity.SP_KEY_ISLOGIN);
        edit.apply();
        LoginActivity.goToLogin(this, false);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(this);
        if (mReceiver != null) {
            unregisterReceiver(mReceiver);
        }
    }

    private CourseDetails mCurrCourseDetail;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCourseDetailChosen(CourseDetails details) {
        mCurrCourseDetail = details;
        TextView tvName = ButterKnife.findById(mBottomSheet, R.id.id_ciw_course_name);
        TextView tvClassroom = ButterKnife.findById(mBottomSheet, R.id.id_ciw_classroom);
        TextView tvWeek = ButterKnife.findById(mBottomSheet, R.id.id_ciw_week);
        TextView tvNumber = ButterKnife.findById(mBottomSheet, R.id.id_ciw_number);
        TextView tvTime = ButterKnife.findById(mBottomSheet, R.id.id_ciw_time);
        TextView tvTeacher = ButterKnife.findById(mBottomSheet, R.id.id_ciw_teacher);
        tvName.setText(details.courseName);
        tvClassroom.setText(details.classRoom);
        tvWeek.setText(details.week);
        tvNumber.setText(details.number);
        tvTime.setText(details.time);
        tvTeacher.setText(details.teacher);
        if (mBottomSheetBehavior != null) {
            needShow = true;
            mBottomSheet.invalidate();
            mBottomSheetPeekHeight = 0;
        }
    }
}
